#include <iostream>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <vector>
#include <stdlib.h>
#include <string>
#include <sstream>
#include <fstream>

int choice = 0;
/*
  Permet de séparer le nom des fichiers appliqué et leur file 
*/
int Split(std::vector<std::string>& vecteur, std::string chaine, char separateur)
{
    vecteur.clear();
    std::string::size_type stTemp = chaine.find(separateur);
    while(stTemp != std::string::npos)
    {
	vecteur.push_back(chaine.substr(0, stTemp));
	chaine = chaine.substr(stTemp + 1);
	stTemp = chaine.find(separateur);
    }
    vecteur.push_back(chaine);
    return vecteur.size();
}

void createCSVFile(const char* dir, std::ofstream& ofs1, std::ofstream& ofs2)
{
    DIR *pDIR;
    struct dirent *entry;
    pDIR=opendir(dir);
    if(!pDIR)
	return;
    while((entry = readdir(pDIR)))
    {
	if( strcmp(entry->d_name, ".") != 0 && 
	    strcmp(entry->d_name, "..") != 0 )
	{
	    std::string path = std::string(dir);
	    std::string name = path + "/" + std::string(entry->d_name);
	    if(std::string(entry->d_name).find(".pgm", 0) != std::string::npos)
	    {
		std::vector<std::string> dirs;
		Split(dirs, path, '/');
		int size = dirs.size();
		std::string num = dirs[size-1].substr(1, std::string::npos);
		int _num = atoi(num.c_str());
		std::ostringstream oss;
		oss<<_num-1;
		name += ";" + oss.str();
		if(choice % 2 == 0)
		    ofs1<<name <<std::endl;
		else ofs2<<name <<std::endl;
		choice++;
	    }
	    createCSVFile(name.c_str(), ofs1, ofs2);
	}
    }
    closedir(pDIR);
}




int main(int argc, char *argv[])
{
    std::ofstream ofs1(argv[2]);
    std::ofstream ofs2(argv[3]);
    createCSVFile(argv[1], ofs1, ofs2);
    return 0;
}
